#!/bin/sh
echo "Starting attestation procedure with PID=$$....."
export LD_LIBRARY_PATH=/usr/lib/rats-tls:$LD_LIBRARY_PATH

ip a
sleep 10
ip a

ip_addr=$(ip a | grep inet | grep -v inet6 | grep -v 127 | awk -F' ' '{print $2}' | awk -F'/' '{print $1}')
if [ "$ip_addr" == "" ]; then
    echo "Cannot not get ip addr."
    exit 1
fi
echo "IP address: $ip_addr"

/usr/bin/virtcca-server -i $ip_addr
exit_status=$?
echo "server return $exit_status"

if [ $exit_status -eq 104 ]; then

    echo "Mounting new root filesystem to /dev/mapper/encryptfs ..."
    cryptsetup luksOpen /dev/vda encryptfs --key-file /root/rootfs_key.bin
    mkdir -p /newroot
    mount /dev/mapper/encryptfs /newroot
elif [ $exit_status -eq 103 ]; then

    echo "Mounting new root filesystem to /dev/vda ..."
    mkdir -p /newroot
    mount /dev/vda /newroot
else
    echo "Other errors, go to panic...."
    exit 1
fi

if [ $? -ne 0 ]; then
    echo "Failed to mount new root filesystem."
    exit 1
fi

exec switch_root /newroot /sbin/init
echo "Failed to switch root!"
exit 0